const Article = require('../Models/article')
const User = require('../Models/user')
const Comment = require('../Models/comment')

// 保存评论
exports.save = async ctx => {
  let message = {
    status: 0,
    msg: "登录才能发表"
  }
  // 验证用户是否登录
  if(ctx.session.isNew) return ctx.body = message

  // 用户登录了
  const data = ctx.request.body

  data.from = ctx.session.uid

  const _comment = new Comment(data)

  await _comment
    .save()
    .then(data => {
      message = {
        status: 1,
        msg: "评论成功"
      }


      // 更新当前 文章 评论数量
      Article
        .updateOne({_id: data.article}, {$inc: {commentNum: 1}}, err => {
          if(err) console.log(err)
          
        })
      
      // 更新用户的 评论计数
      User.updateOne({_id: data.from}, {$inc: {commentNum: 1}}, err => {
        if(err) return console.log(err)
      })

    })
    .catch(err => {
      message = {
        status: 0,
        msg: err
      }
    })

  ctx.body = message
}

// 获取某用户 所有评论
exports.userComments = async ctx => {
  // console.log(ctx.query);
  const uid = ctx.session.uid
  let page = parseInt(ctx.query.page)
  let limit = parseInt(ctx.query.limit)

  page --

  
  const data = await Comment
    .find({"from": uid})
    .sort("-created")
    .skip(page * limit)
    .limit(limit)
    .populate({
      path: "article",
      select: "title"
    })
    .then(data => data)

  const count = data.length

  ctx.body = {
    code: 0,
    msg: "数据请求成功",
    count,
    data: data
  }

}

// 删除评论
exports.amputate = async ctx => {
  const _id = ctx.params.id // 当前comment 的 _id
  let res = {
    state: 1,
    message: "删除成功"
  }

  
  await Comment
    .findById({_id})
    .then(data => data.remove())
    .catch(err => {
      if(err) {
        console.log(err)
        res = {
          state: 0,
          message: "删除未成功"
        }
      }
    })

  ctx.body = res
}
